/**
 * This file showing a simple single client socket server
 */
package v2c03;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author gjunming@gmail.com
 * @version Aug 11, 2009 5:59:16 PM
 */
public class SocketServer {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		try {
			ServerSocket myserver = new ServerSocket(8189);

			// wait for client to connect
			Socket incoming = myserver.accept();
			
			try{
				InputStream in = incoming.getInputStream();
				OutputStream out = incoming.getOutputStream();
				
				Scanner input = new Scanner(in);
				PrintWriter output = new PrintWriter(out,true/*auto flush*/);
				
				output.println("Hello! Enter BYE to exit");
				//echo client input
				boolean done = false;
				while(!done && input.hasNextLine()){
					String line = input.nextLine();
					output.println("Echo From Server:"+line);
					if(line.trim().equalsIgnoreCase("BYE")) {
						done = true;
					}
				}
			} finally {
				incoming.close();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
